<script lang="ts" setup>
import type { MenuItem } from '#/api/system/models';

import { h } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { useVbenForm, z } from '#/adapter/form';
import {
  createMenuApi,
  getMenuListApi,
  updateMenuApi,
} from '#/api/system/menu';
import { IconPicker } from '#/components/icon-picker';
import { toTree } from '#/utils/tree';

defineOptions({ name: 'RoleMenuFormDrawer' });

const emit = defineEmits<{
  complete: [];
}>();

async function onSubmit(values: Record<string, any>) {
  const input = values as MenuItem;
  await (input.id ? updateMenuApi(input) : createMenuApi(input));
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '目录', value: 0 },
          { label: '菜单', value: 1 },
          { label: '按钮', value: 2 },
        ],
      },
      fieldName: 'type',
      label: '菜单类型',
      defaultValue: 1,
      // 占满二列空间 基线对齐
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'TreeSelect',
      componentProps: {
        allowClear: true,
        treeData: [],
        fieldNames: {
          label: 'title',
          value: 'id',
        },
        treeLine: true,
      },
      fieldName: 'parentId',
      label: '上级菜单',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      fieldName: 'title',
      label: '菜单名称',
      rules: 'required',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'name',
      label: '路由名称',
      rules: 'required',
    },
    {
      component: h(IconPicker),
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'icon',
      label: '图标',
      defaultValue: 'ant-design:setting-outlined',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        required(values) {
          return values.type === 1;
        },
        triggerFields: ['type'],
      },
      fieldName: 'path',
      label: '路由路径',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        required(values) {
          return values.type === 1;
        },
        componentProps(values) {
          if (values.type === 0) {
            return { value: 'BasicLayout' };
          }
          return {};
        },
        triggerFields: ['type'],
      },
      fieldName: 'component',
      label: '组件路径',
      help: '菜单类型为目录时,组件路径固定为 BasicLayout',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type === 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'permission',
      label: '权限标识',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'link',
      label: '外链地址',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'iframeSrc',
      label: '内嵌地址',
    },
    {
      component: 'InputNumber',
      fieldName: 'order',
      label: '排序',
      defaultValue: 100,
      rules: z.number().gte(0),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '缓存', value: true },
          { label: '不缓存', value: false },
        ],
      },
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'keepAlive',
      label: '是否缓存',
      defaultValue: false,
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '隐藏', value: true },
          { label: '不隐藏', value: false },
        ],
      },
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'hideInMenu',
      label: '是否隐藏',
      defaultValue: false,
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
    },
  ],
  showDefaultActions: false,
  // 一共二列
  wrapperClass: 'grid-cols-2',
});

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      drawerApi.close();
      emit('complete');
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { values } = drawerApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
        drawerApi.setState({ title: '编辑菜单' });
      }

      // 设置部门列表
      const resp = await getMenuListApi();
      formApi.updateSchema([
        {
          componentProps: {
            treeData: toTree(resp),
          },
          fieldName: 'parentId',
        },
      ]);
    }
  },
  title: '新增菜单',
});
</script>

<template>
  <Drawer>
    <Form />
  </Drawer>
</template>
